package com.dangdang.service.impl;
import com.dangdang.dao.OrderDao;
import com.dangdang.dao.OrderItemDao;
import com.dangdang.entity.Order;
import com.dangdang.entity.OrderItem;
import com.dangdang.service.OrderService;
import com.dangdang.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class OrderServiceImpl implements OrderService {
    public void insert(Order order){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            OrderDao dao = sqlSession.getMapper(OrderDao.class);
            OrderItemDao dao1 = sqlSession.getMapper(OrderItemDao.class);
            dao.insert(order);
            List<OrderItem> orderItemList = order.getOrderItemList();
            for(OrderItem oi:orderItemList){
                oi.setOrder_id(order.getId());
                dao1.insert(oi);
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    public List<Order> selectByUid(int id){
        SqlSession sqlSession = null;
        List<Order> orders = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            OrderDao dao = sqlSession.getMapper(OrderDao.class);
            orders = dao.selectByUid(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return  orders;
    }

    public void changeState(int id){
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            OrderDao dao = sqlSession.getMapper(OrderDao.class);
            dao.changeState(id);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }
}
